﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebLog.Extends
{
    internal class SearchExtend : ExtendBase
    {
        internal static SearchLogHistory searchLogHistoryDistinct(SearchLogHistory history)
        {
            if (history == null || history.searchLogInputs == null || history.searchLogInputs.Count <= 1) return history;
            var gList = history.searchLogInputs.GroupBy(l => l.Memo.IsNullEmpty() ? "" : l.Memo).SelectMany(g => {
                if (g.Key.IsNullEmpty()) return g.AsEnumerable();
                else return g.Reverse().Take(1);
            }).AsEnumerable();//每个备注只保留一条 orderby 会打乱顺序
            gList = gList.OrderBy(l => !l.Memo.IsNullEmpty()).Reverse();
            gList = gList.GroupBy(l => JsonConvert.SerializeObject(l))
                .Select(l => JsonConvert.DeserializeObject<SearchLogInputDto>(l.Key));
            gList = gList.Take(history.Take).Reverse();
            history.searchLogInputs = gList.ToList();//倒过来 分组 取5条 再倒回去 也就是始终取最后面5条
            return history;
        }
        internal static object GetSearchLogDtos(Guid id)
        {
            if (WebLogHelper.GetStatus() == WebLogStatus.TimerRunPause)
                return Comm.TypeFactory.CreateBaseBizResult("日志服务暂停中，可能原因：正在自动删除陈旧日志并整理空间大小！");
            if (WebLogHelper.GetStatus() < WebLogStatus.Runed)
                return Comm.TypeFactory.CreateBaseBizResult("日志服务还未启动，可能原因：正在升级数据结构中！");
            var searchLogHistory = repository.Get<SearchLogHistory>("SearchLogHistory_" + id, new SearchLogHistory());
            searchLogHistoryDistinct(searchLogHistory);//去重
            return searchLogHistory;
        }
        internal static List<SearchLogInputDto> GetSearchLogDtoHistorys(Guid reqId)
        {
            var dates = repository.Get<Dictionary<DateTime, List<SearchLogInputDto>>>("dates_searchLogInputDto_" + reqId, new Dictionary<DateTime, List<SearchLogInputDto>>());
            dates.TryAdd(DateTime.Now.Date, new List<SearchLogInputDto>());
            return dates[DateTime.Now.Date];
        }
        internal static void AppendSearchLogDto(SearchLogInputDto searchLogInputDto)
        {
            var id = searchLogInputDto.wlogid;
            var dates = repository.Get<Dictionary<DateTime, List<SearchLogInputDto>>>("dates_searchLogInputDto_" + id, new Dictionary<DateTime, List<SearchLogInputDto>>());
            dates.TryAdd(DateTime.Now.Date, new List<SearchLogInputDto>());
            dates[DateTime.Now.Date].Add(searchLogInputDto);
            dates.Keys.Where(e => e != DateTime.Now.Date)
                .ToList().ForEach(d => dates.Remove(d));//只留今天的记录
            repository.Set("dates_searchLogInputDto_" + id, dates);
            var searchLogHistory = GetSearchLogDtos(id) as SearchLogHistory;
            if (searchLogHistory == null || searchLogHistory.searchLogInputs == null) return;
            if (!searchLogInputDto.Memo.IsNullEmpty())
            {
                var groups = searchLogHistory.searchLogInputs.FindAll(l => l.Memo == searchLogInputDto.Memo);
                groups.ForEach(g => searchLogHistory.searchLogInputs.Remove(g));//拿走所有的之前这个分组的
            }
            searchLogHistory.searchLogInputs.Add(searchLogInputDto);

            searchLogHistoryDistinct(searchLogHistory);//去重
            searchLogHistory.lastAppendeTime = DateTime.Now;
            repository.Set("SearchLogHistory_" + id, searchLogHistory);
            var dic = repository.Get<Dictionary<Guid, DateTime>>("SearchLogHistoryids", new Dictionary<Guid, DateTime>());
            dic.TryAdd(id, searchLogHistory.lastAppendeTime);
            dic[id] = searchLogHistory.lastAppendeTime;
            repository.Set("SearchLogHistoryids", dic);
        }
    }
    public class SearchLogHistory
    {
        public List<SearchLogInputDto> searchLogInputs { get; set; } = new List<SearchLogInputDto>();
        /// <summary>
        /// 保留多少条元素
        /// </summary>
        public int Take { get; set; } = 10;
        public DateTime lastAppendeTime { get; set; }
    }
}
